/**
 * 摇杆事件
 * Author       : wangjun
 * Date         : 2017-04-11
 */

 

 var com = require('Common')
cc.Class({
    extends: cc.Component,

    properties: {
     
    },

    // use this for initialization
    onLoad: function () {

        this.stick = cc.find('joystick',this.node);
        this.avatar = cc.find('plane_hero/spr_avatar',this.node);
        this._target = cc.find('Map',this.node);
        
        this.stick.on('joystick_move',this.handleJoystick,this);

        this.touchValid = false;
     

        this.node.on('touch',this.onTouch,this);

        this._speed = 5; 
        this.dtime = 0;
        
    },

    handleJoystick: function(event){
        var angle = event.getUserData().angle;
        
        this.avatar.rotation = angle * 180 / Math.PI;
        this.touchValid = true;

    },
    

  onTouch : function(event){
    this.touchValid = false;
  },
  createEnemy : function (dt) {
    
    var enemyId = 0;
    var map = this._target;
    this.dtime += dt;
    if(this.dtime >= 1){
       
        var enemy_x =   Math.random() *1800;
        var enemy_y =   Math.random() * 800;
        cc.loader.loadRes("persist/prefab/plane_enemy", function (err, prefab) {
        com.enemys[enemyId] = cc.instantiate(prefab);
        map.addChild(com.enemys[enemyId]);

        com.enemys[enemyId].setPosition(enemy_x, enemy_y);
        enemyId++;
        });
        this.dtime = 0;
    }
  },
  update: function (dt) {


    var onTouch = this.touchValid;
        if(onTouch){
       var angle = this.avatar.rotation;
       this._target.x += -Math.cos(angle *Math.PI /180) * this._speed;  
       this._target.y += Math.sin(angle *Math.PI /180) * this._speed;
        }
      
        this.createEnemy(dt);
    },

});
